template<class Drawer>
inline TImage<Drawer>::TImage(Texture *texture, int posX, int posY) :
	_texture(texture), _pos(Vector2i(posX, posY))
{
	if(_texture)
	{
		_size = _texture->getSize();
		create();
	}
}

template<class Drawer>
inline TImage<Drawer>::TImage(const char *filename, int posX, int posY) : 
	_texture(NULL), _pos(Vector2i(posX, posY))
{
	load(filename);
}

template<class Drawer>
inline TImage<Drawer>::~TImage()
{
	clear();
}

template<class Drawer>
inline void TImage<Drawer>::load(Texture *texture)
{
	clear();
	_texture = texture;
    if(_texture)
    {
		_size = _texture->getSize();
		create();
	}
}

template<class Drawer>
inline void TImage<Drawer>::load(const char *filename)
{
	clear();
    _texture = MediaManager::instance()->getMedia<Texture>(filename);
    if(_texture)
    {
		_size = _texture->getSize();
		create();
	}
}

template<class Drawer>
inline void TImage<Drawer>::setPosition(int posX, int posY)
{
    _pos.X = posX;
    _pos.Y = posY;
}

template<class Drawer>
inline void TImage<Drawer>::setSize(int width, int height)
{
    _size.X = width;
    _size.Y = height;
    TImage::update();
}

template<class Drawer>
inline const Vector2i &TImage<Drawer>::getSize() const
{
    return _size;
}

template<class Drawer>
inline const Vector2i &TImage<Drawer>::getPosition() const
{
    return _pos;
}

template<class Drawer>
inline Texture *TImage<Drawer>::getTexture()
{
	if(_texture)
		_texture->addRef();
	return _texture;
}

template<class Drawer>
inline void TImage<Drawer>::save(const char *filename)
{
	MediaManager::instance()->saveMedia<Texture>(_texture, filename);
}

template<class Drawer>
inline void TImage<Drawer>::draw()
{
    Renderer *rdr = Renderer::instance();

    rdr->pushMatrix();
    
    rdr->translate(Vector3d(_pos.X, _pos.Y, 0));

    if(_texture) rdr->setTexture(_texture);

    Drawer::draw(4);

    if(_texture) rdr->setTexture(NULL);

    rdr->popMatrix();
}

template<class Drawer>
inline void TImage<Drawer>::create()
{
    _img_pos[0] = 0; _img_pos[1] = 0;
    _img_pos[2] = _size.X; _img_pos[3] = 0;
    _img_pos[4] = _size.X; _img_pos[5] = _size.Y;
    _img_pos[6] = 0; _img_pos[7] = _size.Y;

    _tex_pos[0] = 0; _tex_pos[1] = 0;
    _tex_pos[2] = 1; _tex_pos[3] = 0;
    _tex_pos[4] = 1; _tex_pos[5] = 1;
    _tex_pos[6] = 0; _tex_pos[7] = 1;

    Drawer::initialize(GL_QUADS);
    Drawer::addBuffer(GL_VERTEX_ARRAY, _img_pos, 8*sizeof(float), 2);
    Drawer::addBuffer(GL_TEXTURE_COORD_ARRAY, _tex_pos, 8*sizeof(float), 2);
}

template<class Drawer>
inline void TImage<Drawer>::update()
{
    _img_pos[0] = 0; _img_pos[1] = 0;
    _img_pos[2] = _size.X; _img_pos[3] = 0;
    _img_pos[4] = _size.X; _img_pos[5] = _size.Y;
    _img_pos[6] = 0; _img_pos[7] = _size.Y;

    Drawer::update(GL_VERTEX_ARRAY, _img_pos, 8*sizeof(float));
}

template<class Drawer>
inline void TImage<Drawer>::clear()
{
	if(_texture) _texture->release();
	_texture = NULL;
}
